import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './assetdetail.module.css';
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Tabs, Toast } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import icon_transfer_out from '@/assets/icon_transfer_out.png';
import icon_transfer_in from '@/assets/icon_transfer_in.png';


import NavigateBar from "@/components/NavigateBar";
import { getMyTransactions } from "@/store/actions/user";
import { getAssetDetailInfo, setAssetResultInfo } from "@/utils/storage";
import EmptyView from "@/components/EmptyView/emptyView";
import { LangThai } from "@/utils/langThai";

/**
 * 登录页
 */
export default function AssetDetail() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    // 当前 assets 列表
    const [curAssetList, setCurAssetList] = useState([])

    // 当前 币
    const [curAssetDetail, setCurAssetDetail] = useState({})

    // 文案翻译
    const [curLang, setCurLang] = useState(LangThai);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    // 当前 类型
    let curType = "";

    //清空登录信息
    useEffect(() => {        
        //关闭loading
        setMaskVisible(false)

        // 清空缓存
        setAssetResultInfo(null);

        // 获取详情
        let assetDetailInfo = getAssetDetailInfo();
        setCurAssetDetail(assetDetailInfo);
        doGetMyTransactions(assetDetailInfo.coinType || "");

        //打点
        doHitEvent("ASSET_DETAIL_START")

        return () => {
            //打点
            doHitEvent("ASSET_DETAIL_END")
        }
    }, []);

    // 点击选项卡
    const onHandleTabItemClick = (key) => {
        console.log("点击选项卡: " + key);
        curType = key.toLowerCase();
        doGetMyTransactions(curAssetDetail.coinType || "");
    };

    // 点击列表详情
    const onHandleAssetDetailItemClick = (index) => {
        console.log("点击列表详情: " + index);

        if (curAssetList.length > index) {
            let item = curAssetList[index];

            // 缓存
            setAssetResultInfo(item);

            // 跳转
            history.push('/assetdetailresult');
        }
    };

    // 获取用户交易记录信息 返回
    const onDoGetMyTransactionsCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取币种信息接口 返回: ' + success);

        if (success && data) {

            // 测试
            if (false) {
                for (let i = 0; i < 5; i++) {
                    let inOrOut = "in";
                    if (i % 2 === 0) {
                        inOrOut = "out";
                    }

                    let status = "process";
                    if (i === 0) {
                        status = "succe";
                    } else if (i === 1) {
                        status = "create";

                    } else if (i === 2) {
                        status = "fail";
                    }

                    let item = {
                        address: "addressxxxx",
                        amount: "amountxxx",
                        createTime: "createTimexxx",
                        inOrOut: inOrOut,
                        status: status,
                        symbol: "BTC",
                        txid: "txidxxx",
                    };

                    data.push(item);
                }
            }

            // 处理流程业务
            if (data.length > 0) {
                // {
                //     address: "addressxxxx",
                //     amount: "amountxxx",
                //     createTime: "createTimexxx",
                //     inOrOut: inOrOut,
                //     status: status,
                //     symbol: "BTC",
                //     txid: "txidxxx"
                // };

                // 组装数据
                for (let i = 0; i < data.length; i++) {
                    let item = data[i];
                    item.address = item.address || "";
                    item.createTime = item.createTime || "";
                    item.inOrOut = item.inOrOut || "";
                    item.status = item.status || "";
                    item.symbol = item.symbol || "";
                    item.txid = item.txid || "";

                    let isIn = true;
                    let icon = icon_transfer_in;
                    if (item.inOrOut.indexOf('in') !== -1) {
                        item.amount = "+ " + item.amount;
                        isIn = true;
                    } else {
                        item.amount = "- " + item.amount;
                        isIn = false;
                        icon = icon_transfer_out;
                    }
                    item.isIn = isIn;
                    item.icon = icon;

                    let statusDes = curLang.assetDetailProcessing;//"Processing";
                    if (item.status.indexOf('succe') !== -1) {
                        statusDes = curLang.assetDetailSuccessful;//"Successful";
                    } else if (item.status.indexOf('create') !== -1) {
                        statusDes = curLang.assetDetailProcessing;//"Processing";
                    } else if (item.status.indexOf('fail') !== -1) {
                        statusDes = curLang.assetDetailFailure;//"Failure";
                    }
                    item.statusDes = statusDes;
                }

                // 更新
                setCurAssetList(data);
            }
        }
    };

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取用户交易记录信息
    const doGetMyTransactions = async (coinType) => {
        console.log("doGetMyTransactions: ");
        console.log(curAssetDetail);

        if (!coinType || coinType.length <= 0) {
            Toast.show(curLang.assetDetailTheCoinTypeCanNotBeNull);
            return;
        }

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getMyTransactions(curType, coinType, onDoGetMyTransactionsCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    return (
        <div className="pageRoot pageBackgroundColorGray">
            <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>USDT</NavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumnFull">
                {/* 顶部模块 */}
                <div className={styles.assetDetailTop}>
                    <Tabs
                        style={{
                            'marginTop': '6px',
                            '--title-font-size': '14px',
                            'width': '100%'
                        }}
                        onChange={v => { onHandleTabItemClick(v); }}>
                        <Tabs.Tab title={curLang.assetDetailAll} key='All' />
                        <Tabs.Tab title={curLang.assetDetailOut} key='Out' />
                        <Tabs.Tab title={curLang.assetDetailIn} key='In' />
                        <Tabs.Tab title={curLang.assetDetailFailed} key='Failed' />
                    </Tabs>
                </div>
            </div>

            {/* 列表 */}
            <div className={styles.assetDetailList}>
                <div className={styles.assetDetailListContent}>
                    {curAssetList && curAssetList.map((value, index) => {
                        return (
                            <div className={styles.assetDetailListItem} key={index} onClick={() => { onHandleAssetDetailItemClick(index) }}>
                                <img className={styles.assetDetailListItemIcon} alt="" src={value.icon} />

                                <div className={styles.assetDetailListItemTextRow}>
                                    <div className={styles.assetDetailListItemName}>{value.address}</div>
                                    <div className={styles.assetDetailListItemDetail}>{value.createTime}</div>
                                    {value.isIn && <div className={styles.assetDetailListItemAmountIn}>{value.amount}</div>}
                                    {!value.isIn && <div className={styles.assetDetailListItemAmountOut}>{value.amount}</div>}
                                </div>

                                {value.statusDes === "Processing" && <div className={`${styles.assetDetailListItemStatus} ${styles.assetDetailListItemStatusProcessing}`}>{value.statusDes}</div>}
                                {value.statusDes === "Successful" && <div className={`${styles.assetDetailListItemStatus} ${styles.assetDetailListItemStatusSuccess}`}>{value.statusDes}</div>}
                                {value.statusDes === "Failure" && <div className={`${styles.assetDetailListItemStatus} ${styles.assetDetailListItemStatusFail}`}>{value.statusDes}</div>}

                            </div>
                        )
                    })}
                </div>

                {(!curAssetList || (curAssetList.length === 0)) && <EmptyView></EmptyView>}
            </div>


            {/* 底部 margin */}
            <div className="pageBottomEdge"> </div>

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}